<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author PR
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'_3d:pd:wms3dPdH:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="85%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" ref="formRef">
      <template #wms3dPdSearch>
        <!-- v-auth="'_3d:pd:wms3dPdH:edit'"  -->
        <div class="flex justify-end mt-2" v-if="!!isNewRecord">
          <a-button class="mb-2" @click="handleQuery">
            <Icon icon="ant-design:search-outlined" /> {{ t('查询') }}
          </a-button>
        </div>
      </template>
      <template #wms3dPdCList>
        <BasicTable
          @register="registerWms3dPdCTable"
          @row-click="handleWms3dPdCRowClick"
        />
        <!--<a-button class="mt-2" @click="handleWms3dPdCAdd" v-auth="'_3d:pd:wms3dPdH:edit'" v-if="!!isNewRecord">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>-->
      </template>
      <!-- :auth="'proj:over:pmTermination:edit'"  _3d:pd:wms3dPdH:edit -->
    </BasicForm>
    <ListSelect
      ref="cinvnameListRef"
      v-show="false"
      selectType="basInvSelect"
      :checkbox="true"
      :params="queryParams"
      :selectList="listSelectRef"
    />
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="flow_pd"
        completeText="提交"
        :loading="loadingRef"
        :auth="'_3d:pd:wms3dPdH:edit'"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'Views3dPdWms3dPdHForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed, watchEffect, nextTick, onMounted} from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { Wms3dPdH, wms3dPdHSave, wms3dPdHForm, wms3dPdFindBoxData, wms3dPdHConfirm } from '/@/api/wms/_3d/wms3dPdH';
  import { basWarehousetreeData } from '/@/api/bas/house/basWarehouse';
  import { basInvTreeData } from '/@/api/bas/inv/basInv';
  import { BpmButton } from '/@/components/Bpm';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('_3d.pd.wms3dPdH');
  const { showMessage } = useMessage();
  const record = ref<Wms3dPdH>({} as Wms3dPdH);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增盘点单') : t('编辑盘点单'),
  }));
  // 判断是否为新增
  const isNewRecord = computed(() => record.value.isNewRecord);

  const loadingRef = ref(false);

  let listSelectRef = ref([]);
  let queryParams = ref({});
  const formRef = ref(null);
  let cinvnameListRef = ref<any>('');
  const pdQtyTotal = ref(0); // 新增一个响应式的总和字段

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('仓库编码'),
      field: 'cwhcode',
      component: 'Input',
      componentProps: {
        maxlength: 64,
        readonly: true,
      },
    },
    {
      label: t('仓库名称'),
      field: 'cwhcode',
      fieldLabel: 'cwhname',
      component: 'TreeSelect',
      defaultLabel: '立体仓',
      defaultValue: '13',
      // 默认值
      componentProps: {
        // api: basWarehousetreeData,
        // params: {},
        // canSelectParent: false,
        // allowClear: false,
        disabled: true,
        // 默认值
      },
      itemProps: { validateTrigger: 'blur' },
      required: true,
    },
    {
      label: t('存货编码'),
      field: 'cinvcode',
      component: 'Input',
      componentProps: {
        maxlength: 64,
        readonly: true,
      },
    },
    {
      label: t('存货名称'),
      field: 'cinvcode',
      fieldLabel: 'cinvname',
      component: 'ListSelect',
      componentProps: {
        //maxlength: 100,
        selectType: 'basInvSelect',
        readonly: true,
      },
      required: true,
    },
    {
      label: t('规格型号'),
      field: 'cinvstd',
      component: 'Input',
      componentProps: {
        maxlength: 200,
        readonly: true,
      },
    },
    {
      label: t('批次'),
      field: 'cbatch',
      component: 'Input',
      componentProps: {
        maxlength: 64,
        readonly: true,
      },
    },
    {
      label: t('现存量'),
      field: 'iqty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
        disabled: true,
      },
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
    },
    {
      label: t('实盘数量'),
      field: 'pdQty',
      component: 'Input',
      componentProps: {
        disabled: true,
        
      },
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
    },
    {
      label: t('下架数量'),
      field: 'downQty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
      ifShow: false,
    },
    {
      label: t('上架数量'),
      field: 'upQty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
      ifShow: false,
    },
    {
      label: t('盘点状态'),
      field: 'pdStatus',
      component: 'Input',
      componentProps: {
        maxlength: 10,
      },
      ifShow: false,
    },
    {
      label: t('备注'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
      ifShow: false,
    },
    {
      field: 'wms3dPdSearch',
      component: 'Input',
      slot: 'wms3dPdSearch',
      colProps: { lg: 24, md: 24 },
      // 如果有id，则不显示搜索按钮
      ifShow: (record: Recordable) => !record.id,
    },
    {
      label: t('盘点单子表'),
      field: 'wms3dPdCList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'wms3dPdCList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerWms3dPdCTable, wms3dPdCTable] = useTable({
    // actionColumn: {
    //   width: 60,
    //   // actions: (record: Recordable) => [
    //   //   {
    //   //     icon: 'ant-design:delete-outlined',
    //   //     color: 'error',
    //   //     popConfirm: {
    //   //       title: '是否确认删除',
    //   //       confirm: handleWms3dPdCDelete.bind(this, record),
    //   //     },
    //   //     auth: '_3d:pd:wms3dPdH:edit',
    //   //   },
    //   // ],
    // },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setWms3dPdCTableData(_res: Recordable) {
    wms3dPdCTable.setColumns([
      {
        title: t('关联Id'),
        dataIndex: 'refid',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('boxcode'),
        dataIndex: 'boxcode',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('存货编码'),
        dataIndex: 'cinvcode',
        width: 120,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('存货名称'),
        dataIndex: 'cinvname',
        width: 150,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 200,
        },
        editRule: false,
      },
      {
        title: t('规格型号'),
        dataIndex: 'cinvstd',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 200,
        },
        editRule: false,
      },
      {
        title: t('批次'),
        dataIndex: 'cbatch',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('数量'),
        dataIndex: 'iqty',
        width: 130,
        align: 'right',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
      },
      {
        title: t('实盘数量'),
        dataIndex: 'pdQty',
        width: 130,
        align: 'right',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
      },
      {
        title: t('盈亏数量'),
        dataIndex: 'ykQty',
        width: 130,
        align: 'right',
        editRow: false,
        // editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
        // initialValue: (row) => calculateYkQty(Number(row.iqty), Number(row.pdQty) || 0),
      },
    ]);
    wms3dPdCTable.setTableData(record.value.wms3dPdCList || []);
    // updatePdQty();
    // pdQtyTotal.value = wms3dPdCTable.getDataSource().reduce((acc, curr) => acc + Number(curr.editValueRefs.pdQty), 0);
  }

  function handleWms3dPdCRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleWms3dPdCAdd() {
    wms3dPdCTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleWms3dPdCDelete(record: Recordable) {
    wms3dPdCTable.deleteTableDataRecord(record);
  }

  async function getWms3dPdCList() {
    let wms3dPdCListValid = true;
    let wms3dPdCList: Recordable[] = [];
    for (const record of wms3dPdCTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        wms3dPdCListValid = false;
      }
      wms3dPdCList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of wms3dPdCTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      wms3dPdCList.push({
        ...record,
        status: '1',
      });
    }
    // if (!wms3dPdCListValid) {
    //   throw { errorFields: [{ name: ['wms3dPdCList'] }] };
    // }
    return wms3dPdCList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await wms3dPdHForm(data);
    record.value = (res.wms3dPdH || {}) as Wms3dPdH;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
        console.log('drawer', res);
    setWms3dPdCTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      if(!data.cwhname&&data.cwhcode=='13'){
        data.cwhname = '立体仓';
      }
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.wms3dPdCList = await getWms3dPdCList();

      data.bpm = record.value.bpm; // 流程信息

      data.status = 4; // 提交状态
      loadingRef.value = true;
      const res = await wms3dPdHConfirm(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        console.log('error', error);
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }

  // 查询
  async function handleQuery() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      // console.log('search', data);
      // 删除子表字段
      delete data.wms3dPdCList;
      const res = await wms3dPdFindBoxData(data);
      console.log('search', res);
      record.value = (res.data || {}) as Wms3dPdH;
      setFieldsValue(record.value);
      setWms3dPdCTableData(res);
      showMessage(res.message);
    } catch (error) {
      console.log('error', error);
    } finally {
      console.log('finally');
      setDrawerProps({ confirmLoading: false });
    }
  }

  // 监听子表数据变化
  function watchWms3dPdCTableData() {
    nextTick(() => {
      watchEffect(() => {
        console.log('wms3dPdCTable', wms3dPdCTable);
        const dataSource = wms3dPdCTable?.getDataSource() || [];
        const pdQtySum = dataSource.reduce((acc, curr) => {
          return acc + (Number(curr.editValueRefs?.pdQty) || 0);
        }, 0);
        // 计算盈亏数量
        dataSource.forEach(row => {
          console.log('row', row);
          // const ykQty = calculateYkQty(Number(row.editValueRefs.iqty), Number(row.editValueRefspdQty));
          // 更新表格中的“盈亏数量”字段
        });
        console.log('pdQtySum', pdQtySum);
        pdQtyTotal.value = pdQtySum;
        record.value.pdQty = pdQtySum; // 更新主表的 pdQty 字段
        console.log('pdQtyTotal', pdQtyTotal, record.value,!!formRef.value);

        setFieldsValue(record.value);

        // }
        // 更新表单中的 pdQty 字段
        // updatePdQty(); // 更新表单中的 pdQty 字段
      });
    });
  }
  // 初始化子表后调用监听函数
  function calculateYkQty(iqty: number, pdQty: number): number {
    // pdQty 没有值给一个默认值0
    if (!pdQty) pdQty = 0;
    if (!iqty) iqty = 0;
    return pdQty - iqty;
  }

  // 监听“实盘数量”字段的变化，并更新“盈亏数量”
  function watchPdQtyChanges() {
    nextTick(() => {
      watchEffect(() => {
        const dataSource = wms3dPdCTable?.getDataSource() || [];
        dataSource.forEach(row => {
          const ykQty = calculateYkQty(Number(row.iqty), Number(row.editValueRefs?.pdQty));
          row.ykQty = ykQty;
          // 更新表格中的“盈亏数量”字段
          wms3dPdCTable.updateTableDataRecord(row.id, { ykQty });
        });

      });
    });
  }

  onMounted(() => {
    // watchWms3dPdCTableData();
    // watchPdQtyChanges();
  });
</script>
<style scoped>
  .flex {
    display: flex;
  }
  .justify-end {
    justify-content: flex-end;
  }
</style>
